package ftp

import (
	"encoding/json"
	"fmt"
	"gin/model"
	"math"
	"strconv"
	"strings"
	"time"
)

// 开锁日志
func (p *DataParsing) parsingKillLog(catData []string, ftpInfoId int64) []model.DataKill {
	var logDate, LogTime, steamId, gameName, gameId, eventType, killLocation, jsonStr string
	var killSteamId, killGameName, killGameId, useWeapon, victimLocation, GameTime string

	var dataArr []model.DataKill

	for _, logTxt := range catData {
		//fmt.Println("原始数据", logTxt)

		parts := strings.Split(logTxt, ":")
		//fmt.Println("分割数据", parts)
		timeParts := strings.Split(parts[0], "-")
		//fmt.Println("分割数据2", timeParts)
		//日期转换  年-月-日
		logDate = strings.Replace(timeParts[0], ".", "-", -1)
		//fmt.Println("转换数据1", catDate)
		//时间转换  时:分:秒
		Time := strings.Replace(timeParts[1], ".", ":", -1)
		//fmt.Println("转换数据2", catTime)
		layout := "2006-01-02 15:04:05"
		// 解析时间字符串
		//fmt.Println("解析时间格式为", catDate+" "+catTime)
		t, err := time.Parse(layout, logDate+" "+Time)
		if err != nil {
			fmt.Println("解析时间格式为", err.Error())
			LogTime = "0"
			//return
		}
		// 转换为 Unix 时间戳（秒）

		LogTime = strconv.FormatInt(t.Unix(), 10)
		logTime, _ := strconv.ParseInt(LogTime, 10, 64)
		//太平洋时间制  + 8 小时
		//logTime = logTime + 3600*8
		t = time.Unix(logTime, 0)
		logDate = t.Format("2006-01-02")

		hour, minute, second := t.Clock()
		Time = fmt.Sprintf("%02d:%02d:%02d", hour, minute, second)

		//数据类型过滤
		start := strings.Index(logTxt, ": ")
		if start < 0 {
			jsonStr = ""
		} else {
			jsonStr = logTxt[start+2:]
		}

		if !isJSON(jsonStr) {
			//不是json直接跳过数据
			continue
		}

		jsonBytes := []byte(jsonStr)
		var jsonarr map[string]interface{}
		err = json.Unmarshal(jsonBytes, &jsonarr)
		if err != nil {
			//不是json直接跳过数据
			continue
		}
		//fmt.Println("原始数据", logTxt)
		//fmt.Println("原始数据", jsonarr["Killer"].(map[string]interface{}))
		//bool 转换成 字符串
		eventType = fmt.Sprintf("%t", jsonarr["Killer"].(map[string]interface{})["IsInGameEvent"].(bool))
		gameName = jsonarr["Killer"].(map[string]interface{})["ProfileName"].(string)
		steamId = jsonarr["Killer"].(map[string]interface{})["UserId"].(string)

		killGameName = jsonarr["Victim"].(map[string]interface{})["ProfileName"].(string)
		killSteamId = jsonarr["Victim"].(map[string]interface{})["UserId"].(string)

		GameTime = jsonarr["TimeOfDay"].(string)
		useWeapon = jsonarr["Weapon"].(string)
		x := jsonarr["Killer"].(map[string]interface{})["ClientLocation"].(map[string]interface{})["X"].(float64)
		y := jsonarr["Killer"].(map[string]interface{})["ClientLocation"].(map[string]interface{})["Y"].(float64)
		z := jsonarr["Killer"].(map[string]interface{})["ClientLocation"].(map[string]interface{})["Z"].(float64)
		killLocation = "X=" + fmt.Sprintf("%f", x) + " Y=" + fmt.Sprintf("%f", y) + " Z=" + fmt.Sprintf("%f", z)

		killX := jsonarr["Victim"].(map[string]interface{})["ClientLocation"].(map[string]interface{})["X"].(float64)
		killY := jsonarr["Victim"].(map[string]interface{})["ClientLocation"].(map[string]interface{})["Y"].(float64)
		killZ := jsonarr["Victim"].(map[string]interface{})["ClientLocation"].(map[string]interface{})["Z"].(float64)
		victimLocation = "X=" + fmt.Sprintf("%f", killX) + " Y=" + fmt.Sprintf("%f", killY) + " Z=" + fmt.Sprintf("%f", killZ)

		//三维空间坐标  取2点之间距离
		ax := killX
		bx := x

		ay := killY
		by := y

		az := killZ
		bz := z

		distance := math.Sqrt(math.Pow(ax-bx, 2) + math.Pow(ay-by, 2) + math.Pow(az-bz, 2))
		distance = distance / 100

		distance = roundToTwoDecimals(distance)

		gameName = TruncateStringByCharCount(gameName, 50)

		// 输出字节集（以十六进制表示）
		//fmt.Printf("Byte slice: %x\n", byteSlice)

		// 将字节集转换回字符串
		gameName = filterInvalidChars(gameName)

		killGameName = TruncateStringByCharCount(killGameName, 50)

		// 输出字节集（以十六进制表示）
		//fmt.Printf("Byte slice: %x\n", byteSlice)

		// 将字节集转换回字符串
		killGameName = filterInvalidChars(killGameName)

		gameId, _ := strconv.ParseInt(gameId, 10, 64)
		killGameId, _ := strconv.ParseInt(killGameId, 10, 64)
		distanceStr := fmt.Sprintf("%.2f", distance)
		downloadFile := model.DataKill{
			FtpInfoId:      ftpInfoId,
			Date:           logDate,
			Time:           Time,
			LogTime:        logTime,
			SteamId:        steamId,
			GameName:       gameName,
			GameId:         gameId,
			KillerGameId:   killGameId,
			KillerSteamId:  killSteamId,
			KillerGameName: killGameName,
			KillerLocation: killLocation,
			VictimLocation: victimLocation,
			KillDistance:   distanceStr,
			UseWeapon:      useWeapon,
			EventType:      eventType,
			GameTime:       GameTime,
		}
		dataArr = append(dataArr, downloadFile)
	}
	return dataArr
}

type result interface {
}

func isJSON(s string) bool {
	var js map[string]interface{}
	err := json.Unmarshal([]byte(s), &js)
	return err == nil
}

// 四舍五入取小数点后2位
func roundToTwoDecimals(num float64) float64 {
	// 将num乘以100，四舍五入到最近的整数，然后再除以100
	return math.Round(num*100) / 100
}
